class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        int n = words.size();
        unordered_map<string, int> mp;
        for(int i = 0; i < n; ++i)
        {
            mp[words[i]]++;
        }

        vector<pair<string, int>> vt(mp.begin(), mp.end());

        sort(vt.begin(), vt.end(), [&](const auto& e1, const auto& e2){
            return e1.second > e2.second || (e1.second == e2.second && e1.first < e2.first);
        });

        vector<string> ans(k);
        for(int i = 0; i < k; ++i)
        {
            ans[i] = vt[i].first;
        }

        return ans;
    }
};
